<?php

require_once 'BasicController.php';

class AuthController extends Zend_Controller_Action
{

	public function init()
	{
		/* Initialize action controller here */
	}

	public function indexAction()
	{
		$this->_forward('login');
	}

	//ACTION PARA EFETUAR O LOGIN DO USUÁRIO
	public function loginAction()
	{
		if($_POST){// Verifica se o usuario informado existe no banco de dados

			try{
				$auth = new UserBusiness();

				//Recupera os valores informados no form
				$formData = $this->getRequest()->getPost();
				$email = $formData['email'];
				$password = $formData['pass'];

				$personData = $auth->getUserByEmail($email);

				//Verifica se o usuario existe na base
				if($personData){
					if($personData['us_status'] == 1){


						if($this->comparePass($password, $personData)){
							//Guarda os dados do usuario em um array
							$personDataArray = array(
								"idt_client" => $personData['idt_client'],
								"login" => $personData['login'],
								"name" 	=> $personData['name'],
								"email" => $personData['email'],
								"phone" => $personData['phone'],
								"user_type" => $personData['us_type']
							);

							$auth->updateLastAccess($personData['idt_client']);

							Zend_Auth::getInstance()->getStorage()->write($personDataArray);

							//$this->_redirect('products');
						}else{
							$this->view->login = $email;
							$this->view->authErrorMessage = "Senha inválida!";
							return;
						}
							
					}else{
						$this->view->login = $email;
						$this->view->authErrorMessage = "Conta não confirmada!";
						return;
					}
				}else{
					$this->view->login = $email;
					$this->view->authErrorMessage = "Usuário inválido!";
					return;
				}
			}catch (Exception $e){
				echo $e;
			}
		}
	}

	public function comparePass($passwd, $personData){

		$salt = md5($personData['register_date']);

		$pass = crypt($passwd,$salt);

		$pass = hash('sha512',$pass);

		if($pass == $personData['password']){
			return true;
		}else{
			return false;
		}

	}

}

